@echo off
REM DW SQL脚本管理工具开发环境设置脚本 (Windows)

echo 🚀 Setting up DW SQL Script Manager development environment...

REM 检查Docker是否安装
docker --version >nul 2>&1
if errorlevel 1 (
    echo ❌ Docker is not installed. Please install Docker first.
    exit /b 1
)

docker-compose --version >nul 2>&1
if errorlevel 1 (
    echo ❌ Docker Compose is not installed. Please install Docker Compose first.
    exit /b 1
)

REM 创建环境变量文件
if not exist .env (
    echo 📝 Creating .env file from template...
    copy .env.example .env
    echo ✅ .env file created. Please review and update the configuration.
)

REM 启动数据库服务
echo 🐳 Starting database services with Docker Compose...
docker-compose -f docker-compose.dev.yml up -d

REM 等待数据库启动
echo ⏳ Waiting for databases to be ready...
timeout /t 10 /nobreak >nul

REM 检查数据库健康状态
echo 🏥 Checking database health...
set max_attempts=30
set attempt=1

:check_postgres
docker-compose -f docker-compose.dev.yml exec -T postgres pg_isready -U postgres -d dw_sql_manager >nul 2>&1
if errorlevel 0 (
    echo ✅ PostgreSQL is ready
    goto check_redis
)

if %attempt% geq %max_attempts% (
    echo ❌ PostgreSQL failed to start after %max_attempts% attempts
    exit /b 1
)

echo ⏳ Waiting for PostgreSQL... (attempt %attempt%/%max_attempts%)
timeout /t 2 /nobreak >nul
set /a attempt+=1
goto check_postgres

:check_redis
docker-compose -f docker-compose.dev.yml exec -T redis redis-cli ping >nul 2>&1
if errorlevel 0 (
    echo ✅ Redis is ready
) else (
    echo ❌ Redis is not responding
    exit /b 1
)

REM 安装后端依赖
if exist backend (
    echo 📦 Installing backend dependencies...
    cd backend
    npm install
    cd ..
)

REM 安装前端依赖
if exist frontend (
    echo 📦 Installing frontend dependencies...
    cd frontend
    npm install
    cd ..
)

echo 🎉 Development environment setup completed!
echo.
echo 📋 Next steps:
echo   1. Review and update .env file if needed
echo   2. Run 'npm run test:db' in backend directory to test database connections
echo   3. Run 'npm run dev' in backend directory to start the backend server
echo   4. Run 'npm run dev' in frontend directory to start the frontend server
echo.
echo 🔗 Useful URLs:
echo   - pgAdmin: http://localhost:8080 (admin@example.com / admin123)
echo   - Redis Commander: http://localhost:8081
echo   - Backend API: http://localhost:3000
echo   - Frontend: http://localhost:5173

pause